<template>
  <c-loading :loading="loading">
    <view class="container goods-info">
      <c-swiper :list="info?.bannerImgs">
        <template #default="{ item }">
          <c-img :src="item" class="branner-img" mode="aspectFill" />
        </template>
      </c-swiper>
      <view class="goods-body block">
        <view class="flex-between al-center">
          <c-number class="sale-price bold" :value="info?.minPrice" prefix="￥" />
          <c-number class="color-gray mini text-del" :prefix-mini="false" style="margin-left: 10px" :value="info?.msrp" prefix="￥" />
          <view class="grow"></view>
          <view class="font-mini color-gray">
            {{ info?.sales }}
            人已购买
          </view>
        </view>
        <view class="flex al-start" style="margin-top: 12px">
          <view class="row3 goods-name grow">{{ info?.goodsName }}</view>
          <view class="collects">
            <c-icon :icon="isCollects ? 'heart-filled' : 'heart'" @tap="onCollect" color="#F30240" :size="52" />
          </view>
        </view>
      </view>

      <!-- <image class="ads" src="/assets/1716884763277.png" mode="widthFix" /> -->

      <view class="block goods-rows">
        <view class="goods-item flex-center" v-if="couponList.length" @tap="showCoupon = true">
          <view class="label">领券</view>
          <view class="grow tickets">
            <view class="ticket" v-for="c in couponList" :key="c.id">{{ getCouponName(c) }}</view>
          </view>
          <c-icon class="arrow" icon="chevron-right" />
        </view>
        <!-- <view class="goods-item">
          <view class="label">促销</view>
          <view class="grow">红色、白色</view>
        </view> -->
        <view class="goods-item" v-if="specProps" @tap="toConfirm(true)">
          <view class="label">规格</view>
          <view class="grow">{{ specProps }}</view>
          <c-icon class="arrow" icon="chevron-right" />
        </view>
        <view class="goods-item" @tap="showService = true" v-if="info?.goodsService?.length">
          <view class="label">服务</view>
          <view class="grow">
            {{
              info.goodsService
                .map(a => a.name)
                .slice(0, 2)
                .join('、')
            }}
          </view>
          <c-icon class="arrow" icon="chevron-right" />
        </view>
      </view>
      <view class="block goods-brand" v-if="brandInfo" @tap="toGoodsList(brandInfo.id)">
        <c-img class="brand-img" :src="brandInfo.logo"></c-img>
        <view class="grow">
          <view class="brand-name">{{ brandInfo.brandName }}</view>
          <view class="brand-desc">{{ `在售${brandInfo.goodsCount}件商品` }}</view>
        </view>
        <view class="rights">
          逛逛品牌
          <c-icon icon="chevron-right" size="30" />
        </view>
      </view>
      <view class="block" v-if="evaluateSome.count">
        <view class="title">
          评价（{{ evaluateCount }}）
          <view class="more" @tap="router.push('/pagesBus/evaluate/index?id='+info.id)">
            全部
            <c-icon icon="chevron-right" />
          </view>
        </view>
        <view class="evaluate-wrap">
          <view class="evaluate" v-for="item in evaluateSome.list" :key="item.id">
            <c-img class="evaluate-head" default-src="/assets/imgs/default/avatar.png" :src="item.userAvatarUrl" />
            <view class="evaluate-body">
              <view class="evaluate-name">{{ item.userNickName }}</view>
              <view class="evaluate-text">
                {{ item.evaluateContent }}
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="block detail">
        <view class="title">详细信息</view>
        <view class="goods-attrs" v-if="goodsProps">
          <view class="goods-item" v-for="(item, key) in goodsProps" :key="key">
            <view class="label">{{ key }}</view>
            <view class="grow">{{ item.join('、') }}</view>
          </view>
        </view>
        <view class="goods-detail-imgs">
          <c-img v-for="(img, i) in info?.goodsDetailImgs ?? []" class="img" mode="widthFix" :src="img" :key="i" />
        </view>
      </view>
      <view class="fixed-btn-group">
        <button class="fixed-btn clearbtn" @tap="onShare" hover-class="view-hover">
          <c-icon icon="jump" />
        </button>
      </view>
      <view class="fixed-footer shadow">
        <c-badge :hide="!cartNum" :number="cartNum" offset-x="-6rpx">
          <view class="footer-btn" hover-class="view-hover" @tap="router.push('./cart')">
            <image class="img" src="/assets/imgs/cart.png" />
            <view class="text">购物车</view>
          </view>
        </c-badge>
        <view class="grow"></view>
        <c-button size="inline" class="round clearbtn" @tap="toConfirm(true)" type="primary" plain>加入购物车</c-button>
        <c-button size="inline" class="round" @tap="toConfirm(false)" type="primary">立即购买</c-button>
      </view>
      <view class="end"></view>
    </view>
    <template #popup>
      <sku-popup v-model="show" v-bind="info ?? {}" :btn-text="isCart ? '加入购物车' : '立即购买'" @confirm="onConfirm"></sku-popup>
      <service-popup v-model="showService" :services="info?.goodsService"></service-popup>
      <share-popup
        code="Goods"
        path="pages/goods/info"
        :append-id="info?.id"
        :data="{ ...info, salePrice: `￥${info?.minPrice}`, smallImg: (info?.bannerImgs ?? [])[0] }"
        ref="shareRef"
      ></share-popup>
      <coupon-popup v-model="showCoupon" :coupon-list="couponList"></coupon-popup>
    </template>
  </c-loading>
</template>
<script setup>
import { CButton, CLoading, CImg, CSwiper, CNumber, CIcon, CBadge } from '@/components';
import { afterLogin, useLoading, useRouter } from '@/hooks';
import { View, Button, Image } from '@tarojs/components';
import api from '@/api';
import { unShort } from '@/utils';
import { computed, ref, shallowRef } from 'vue';
import SkuPopup from './components/sku-popup.vue';
import ServicePopup from './components/service-popup.vue';
import CouponPopup from './components/coupon-popup.vue';
import SharePopup from '@/pages/my/components/share-popup.vue';
import toast from '@/utils/toast';
import { useShareTimeline, useDidHide } from '@tarojs/taro';

const router = useRouter();
const info = ref(null);
const brandInfo = ref(null);
const show = ref(false);
const isCart = ref(true);
const isCollects = ref(false);
const showService = ref(false);
const showCoupon = ref(false);
const cartNum = ref(null);
const shareRef = shallowRef();
const couponList = ref([]);

const evaluateSome = ref({});

const evaluateCount = computed(() => {
  if (evaluateSome.value.count >= 1000) {
    return '1000+';
  }
  if (evaluateSome.value.count >= 500) {
    return '500+';
  }
  if (evaluateSome.value.count >= 200) {
    return '200+';
  }
  if (evaluateSome.value.count >= 100) {
    return '100+';
  }
  return evaluateSome.value.count;
});
const onShare = () => {
  shareRef.value.show();
};

const getCouponName = item => {
  if (!item) return '-';
  if (item.couponType == 1) {
    if (item.threshold) {
      return `满${item.threshold}打${item.discountValue}折`;
    }
    return `${item.discountValue}折`;
  } else {
    if (item.threshold) {
      return `满${item.threshold}减${item.discountValue}`;
    }
    return `立减${item.discountValue}元`;
  }
};
const { loading, options } = useLoading(async options => {
  if (options?.scene) {
    options.scene = options.scene.split('_')[1];
    options.id = unShort(options.scene);
  }
  await afterLogin();
  info.value = await api.goods.goodsGetDetail({ id: options.id });
  info.value.goodsService = [
    { name: '正品保证', value: '在此小程序下单均为正品' },
    { name: '免费包邮', value: '购买当前商品可免邮费' },
    { name: '7天无理由退款', value: '当前商品支持7天内无理由退款' },
    {
      name: '闪电发货',
      value: '24小时内立即发货'
    }
  ];
  loadCartCount();
  collectsActive(options.id);
  couponList.value = await api.mk.couponGetByGoods({ id: info.value.id, value: info.value.brandId });
  if (info.value.brandId) brandInfo.value = await api.goods.goodsBrandInfo({ id: info.value.brandId });
  await loadEvaluate(options.id);
});

useDidHide(() => {
  if (loading.value) {
    loadCartCount();
  }
});

const loadEvaluate = async goodsId => {
  evaluateSome.value = await api.evaluate.evaluateSome({ id: goodsId });
};
const onCollect = () => {
  api.goods[isCollects.value ? 'collectsRemove' : 'collectsAdd']({ id: options.value.id }).then(r => {
    isCollects.value = !isCollects.value;
    if (!isCollects.value) {
      toast.success('取消收藏');
    } else {
      toast.success('收藏成功');
    }
  });
};
const loadCartCount = async () => {
  cartNum.value = await api.goods.cartCount();
};

useShareTimeline(() => {
  return {
    title: info.value?.goodsName,
    query: `id=${info.value?.id}&uid=${info.value?.userId}`
  };
});

const specProps = computed(() => {
  if (!info.value?.specProps) return false;
  return info.value?.specProps?.map(a => a.name)?.join('、');
});

const goodsProps = computed(() => {
  if (!info.value?.goodsProps) return false;
  return info.value.goodsProps.groupBy(
    a => a.name,
    a => a.value
  );
});

const toGoodsList = id => {
  router.push('/pages/goods/index?bid=' + id);
};

const collectsActive = async id => {
  isCollects.value = await api.goods.collectsActive({ id });
};
const toConfirm = cart => {
  isCart.value = cart;
  show.value = true;
};

const onConfirm = async ({ sku, qty }) => {
  if (isCart.value) {
    await api.goods
      .cartAdd({
        id: sku.id,
        value: qty
      })
      .success('已加入您的购物车', true)
      .error();
    loadCartCount();
  } else {
    router.push('/pagesOrder/order/confirm', {
      items: [
        {
          skuId: sku.id,
          qty
        }
      ]
    });
  }
};
</script>
<style lang="scss">
.goods-info {
  .branner-img {
    width: 100%;
    height: 100%;
  }
  .ads {
    width: 100%;
    margin-bottom: 20px;
  }
  .tickets {
    margin-right: -15px;
    display: flex;
    overflow: hidden;
    align-items: center;
    .ticket {
      display: inline-block;
      padding: 0 30px;
      background-color: var(--color-danger);
      color: var(--color-caption);
      font-size: 20px;
      line-height: 40px;
      border-radius: 8px;
      flex-shrink: 0;
      margin-right: 15px;
    }
  }

  .evaluate {
    display: flex;
    margin-bottom: 10px;
    .evaluate-head {
      flex-shrink: 0;
      height: 60px;
      width: 60px;
      margin-right: 20px;
      border-radius: 50%;
    }
    .evaluate-body {
      flex-grow: 1;
      .evaluate-name {
        font-size: 24px;
        color: var(--color-gray);
        margin-bottom: 10px;
      }
      .evaluate-text {
        font-size: 26px;
        line-height: 1.6em;
      }
    }
  }
  .collects {
    padding: 0px 10px;
    font-weight: bold;
    flex-shrink: 0;
  }
  .block {
    padding: 20px 30px;
    border-radius: 10px;
  }
  .detail.block {
    margin-bottom: 0;
    padding-bottom: 0;
  }
  .goods-body {
    .sale-price {
      font-weight: bold;
      font-size: 48px;
      color: var(--color-danger);
    }
    .goods-name {
      line-height: 44px;
    }
  }
  .title {
    font-weight: bold;
    margin-bottom: 25px;
    position: relative;
    .more {
      position: absolute;
      font-weight: normal;
      font-size: 22px;
      color: var(--color-gray);
      display: flex;
      align-items: center;
      width: 100px;
      justify-content: space-between;
      padding: 10px;
      right: 0;
      top: 0;
    }
  }

  .goods-item {
    display: flex;
    align-items: center;
    height: 74px;
    line-height: 44px;
    font-size: 26px;
    .label {
      font-weight: 500;
      color: var(--color-default);
      flex-shrink: 0;
      min-width: 5em;
    }
    .arrow {
      flex-shrink: 0;
    }
  }
  .goods-detail-imgs {
    margin: 10px -30px 0;
    .img {
      width: 100%;
    }
  }
}
.goods-brand {
  display: flex;
  align-items: center;
  .brand-img {
    width: 100px;
    height: 100px;
    border-radius: 10px;
    overflow: hidden;
    flex-shrink: 0;
    margin-right: 15px;
  }
  .brand-name {
    font-size: 32px;
    margin-bottom: 8px;
  }
  .brand-desc {
    font-size: 22px;
    color: var(--color-gray);
  }
  .rights {
    display: flex;
    font-size: 22px;
    color: var(--color-gray);
    align-items: center;
  }
}
.fixed-btn-group {
  position: fixed;
  right: 30px;
  bottom: calc(30px + 110px + var(--safe-bottom));
  .fixed-btn {
    border-radius: 50%;
    width: 72px;
    height: 72px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--color-caption);
    box-shadow: 0 0px 10px rgba(0, 0, 0, 0.1);
  }
}
.fixed-footer {
  height: 120px;
  .footer-btn {
    padding: 10px 20px;
    text-align: center;
    font-size: 20px;
    .img {
      height: 42px;
      margin: 0 auto 2px;
      width: 42px;
    }
  }
  .round {
    width: 240px;
    height: 74px;
    font-size: 28px;
    line-height: 74px;
    padding: 0;
  }
  & + .end {
    height: 120px;
  }
}
</style>
